// pages/home/detail/detail.js
var util = require('../../../utils/util.js');
//录音对象
const recorderManager = wx.getRecorderManager()
const innerAudioContext = wx.createInnerAudioContext()
const app=getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    CustomBar: app.globalData.CustomBar,
    add:false,
    sound:false,
    messages:[],
    recordState:false,
    width:0,
    list:[],
    backgroundUrl: app.globalData.backgroundPic,
    type:'',
    self:false,
    id:'',
    roomId:'',
    friend:false,
    info:[],
    delete:false,
    bgimg1: app.globalData.bgimg,
    haveImg: app.globalData.haveImg,
    vedio_pic:'',
    vedio:''


  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    var that =this
    //不要在意 可能会因为 空报错
    //得到传递的参数
    console.log(options.info)
    var info = JSON.parse(options.info)
    console.log(info)
    that.data.type = info.type
    that.data.info = info

    that.setData({
      info:info,
      bgimg1: app.globalData.bgimg,
      haveImg: app.globalData.haveImg
    })
    if (info.type=='friend')
    {
      that.data.roomId =-info.id
    }
    else{
      if (info.creatorid==app.globalData.userInfo.userInfo.id){
      that.setData({
        delete:true
      })
      }
      that.data.roomId = info.id
    }

    //更新历史消息
    wx.request({
      // url: 'https://mockapi.eolinker.com/SN5C9Ybd511179abd037ba7a2443cbd1f4885103f842b3e/chat/getHistoryMessage',
      url: 'https://sdu-miniprogram.cn:8888/api/miniprogram/chatInfo/getHistoryMessage',
      method:'POST',
      data:{
        token: app.globalData.userInfo.token,
        roomId: that.data.roomId
      },
      success:function(res)
      {
        console.log(app.globalData.id)
        //反过来好
        console.log(res.data.list.reverse())
        // that.data.list= res.data.list
        var temp = res.data.list
        for(var i=0;i<res.data.list.length;i++)
        {
          if (temp[i].type == "LOCATION") 
          {
            var temp2 = JSON.parse(temp[i].content)
            temp[i].address = temp2.name
            temp[i].latitude=temp2.latitude
            temp[i].longitude=temp2.longitude
            console.log(temp.address)
          }
          
         
        }
        that.setData({
          list: temp,
          id: app.globalData.userInfo.userInfo.id
        })
      }
    })
    
    //查看历史消息不收即时的消息
    if (that.data.type == 'room'){
    //监听聊天
    var roomId = that.data.roomId
    var channel = "group" + roomId
    app.globalData.goEasy.subscribe({
      channel: channel, //替换为您自己的channel
      onMessage: function (message) {
        // console.log(message)
        console.log("Channel:" + message.channel + " content:" + message.content);
        var json = JSON.parse(message.content)
        console.log(json)
        if (json.type == "LOCATION") {
          console.log(json.content)
          // var temp2 = JSON.parse(json.content)
          var temp2=json.content
          json.address = temp2.name
          json.latitude = temp2.latitude
          json.longitude = temp2.longitude
        }

        that.data.list.push(json)
        //可以不断当前页面积累接受消息
        console.log(that.data.list)
        that.setData({
          list: that.data.list
        })
      }
    });
    }
    else{
      //监听聊天
      var roomId = that.data.roomId
      var channel = "private" + app.globalData.userInfo.userInfo.id + that.data.info.id
      app.globalData.goEasy.subscribe({
        channel: channel, //替换为您自己的channel
        onMessage: function (message) {
          // console.log(message)
          console.log("Channel:" + message.channel + " content:" + message.content);
          var json = JSON.parse(message.content)
          console.log(json)
          that.data.list.push(json)
          // var messages = that.data.messages
          //可以不断当前页面积累接受消息
          // messages.push(json);
          that.setData({
            // message: messages,
            list: that.data.list
          })
        }
      });
      this.pageScrollToBottom()
    }
    

  },
  hideModal(e) {
    this.setData({
      add: null
    })
  },
  checkLocation:function(e)
  {
    //查看位置
    console.log(e)
    wx.openLocation({
      latitude: e.currentTarget.dataset.latitude,
      longitude: e.currentTarget.dataset.longitude
    })

  },
  addmore:function()
  {
    this.setData({
      add:true
    })
  },
  delete:function()
  {
    var token=app.globalData.userInfo.token
    var roomId=this.data.info.id

  },
  changeSound:function()
  {
    var sound=this.data.sound
    this.setData({
      sound:!sound
    })

  },
  changeToself:function(e)
  {
    // console.log(this.data.self)
    this.setData({
      self:!this.data.self
    })

  },
  send:function(e)
  {
    this.setData({
      inputInit:'',
    })
    var token = app.globalData.userInfo.token
    var type='TEXT'
    var content = e.detail.value
    var sender = app.globalData.userInfo.userInfo.id
    var roomId=this.data.roomId
    var sendTime = util.formatTime(new Date());
    var senderAvatar = app.globalData.userInfo.userInfo.avatar
    var id=app.globalData.userInfo.userInfo.id

    // console.log(e.detail.value)
    // console.log(roomId)
    // console.log(sendTime)
    // console.log(channel)
    var json={
      id: id,
      roomId:roomId,
      type: 'TEXT',
      senderAvatar: app.globalData.userInfo.userInfo.avatar,
      sendTime:sendTime,
      content: e.detail.value,
      sender: app.globalData.userInfo.userInfo.id
    }
    if (this.data.type=='friend')
    {
      var channel = "private" + app.globalData.userInfo.userInfo.id+this.data.info.id
      var receiver = this.data.info.id
    }
    else{
      var channel = "group" + roomId
      var receiver = ''
    }

    app.globalData.goEasy.publish({
      channel: channel, //替换为您自己的channel
      message: JSON.stringify(json)//替换为您想要发送的消息内容
    });
    wx.request({
      url: 'https://sdu-miniprogram.cn:8888/api/miniprogram/chatInfo/sendMessage',
      method:'POST',
      data:{
        token:token,
        message:{
          id:id,
          roomId:roomId,
          type:type,
          sendTime:sendTime,
          content:content,
          sender:sender,
          receiver: receiver,
          senderAvatar:senderAvatar
        }
      },
      success:function(res){
        console.log(res)
      }

    })

    
   
  },
  containerTap: function (res){
    this.setData({
      add: false
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  goTosetting:function()
  {
    
    //传参
    let info = JSON.stringify(this.data.info)
    wx.navigateTo({
      url: '/pages/others/setting/setting?info='+info
    })

  },
  goToscan:function()
  {
    wx.scanCode({
      success: function (res) {
        console.log(res)
      }
    })
  },
  inputWord:function(e)
  {
    console.log(e)

  },
  goTolocation:function(e)
  {
    //位置信息
    var token = app.globalData.userInfo.token
    var type = 'LOCATION'
    var content = e.detail.value
    var sender = app.globalData.userInfo.userInfo.id
    var roomId = this.data.roomId
    var sendTime = util.formatTime(new Date());
    var senderAvatar = app.globalData.userInfo.userInfo.avatar
    var id = app.globalData.userInfo.userInfo.id
    if (this.data.type == 'friend') {
      var channel = "private" + app.globalData.userInfo.userInfo.id + this.data.info.id
      var receiver = this.data.info.id
    }
    else {
      var channel = "group" + roomId
      var receiver = ''
    }

    wx.chooseLocation({
      success: function(res) {
        console.log(res)
        //同步
        var json = {
          id: id,
          roomId: roomId,
          type: 'LOCATION',
          senderAvatar: app.globalData.userInfo.userInfo.avater,
          sendTime: sendTime,
          content: res,
          sender: app.globalData.userInfo.userInfo.id
        }

        app.globalData.goEasy.publish({
          channel: channel, //替换为您自己的channel
          message: JSON.stringify(json)//替换为您想要发送的消息内容
        });

        //传到服务器
        wx.request({
          url: 'https://sdu-miniprogram.cn:8888/api/miniprogram/chatInfo/sendMessage',
          method: 'POST',
          data: {
            token: token,
            message: {
              id: id,
              roomId: roomId,
              type: type,
              sendTime: sendTime,
              content: res,
              sender: sender,
              receiver: receiver,
              senderAvatar: senderAvatar
            }
          },
          success: function (res) {
            console.log(res)
          }
      })
      },
    })
  },
  goTofile:function(e)
  {
    var that =this
    if (that.data.type == 'room') {
      var receiver = ''
      var channel = "group" + that.data.roomId
    }
    else {
      var channel = "private" + app.globalData.userInfo.userInfo.id + that.data.info.id
      var receiver = that.data.info.id
    }
    var token = app.globalData.userInfo.token
    var type = 'FILE'
    var sender = app.globalData.userInfo.userInfo.id
    var roomId = that.data.roomId
    var sendTime = util.formatTime(new Date());
    var senderAvatar = app.globalData.userInfo.userInfo.avatar
    var id = app.globalData.userInfo.userInfo.id
    wx.chooseMessageFile({
      count: 10,
      // type: 'file',
      success:function(e)
      {
        console.log(e)
        //同步聊天
        // var tempFilePaths =e.tempFiles
        for (var i = 0; i < e.tempFiles.length;i++)
        {
          wx.uploadFile({
            url: 'https://sdu-miniprogram.cn:8888/api/miniprogram/fileInfo/upload',
            filePath: e.tempFiles[i].path,
            header: {
              "Content-Type": "multipart/form-data"
            },
            name: 'myFile',
            success:function(res)
            {
              var data = JSON.parse(res.data)
              console.log(data)
              //同步聊天
              var json = {
                id: id,
                roomId: roomId,
                type: 'FILE',
                senderAvatar: app.globalData.userInfo.userInfo.avatr,
                sendTime: sendTime,
                content: data.url,
                sender: app.globalData.userInfo.userInfo.id
              }
              app.globalData.goEasy.publish({
                channel: channel, //替换为您自己的channel
                message: JSON.stringify(json)//替换为您想要发送的消息内容
              });

              wx.request({
                url: 'https://sdu-miniprogram.cn:8888/api/miniprogram/chatInfo/sendMessage',
                method: 'POST',
                data: {
                  token: token,
                  message: {
                    id: id,
                    roomId: roomId,
                    type: type,
                    sendTime: sendTime,
                    content: data.url,
                    sender: sender,
                    receiver: receiver,
                    senderAvatar: senderAvatar
                  }
                },
                success: function (res) {
                  console.log(res)
                }
              })
            }
          })
        }
      }
    })
    
  },
  goTopic:function()
  {
    //发送图片
    var that =this
    if (that.data.type == 'room') {
      var receiver = ''
      var channel = "group" + that.data.roomId
    }
    else {
      var channel = "private" + app.globalData.userInfo.userInfo.id + that.data.info.id
      var receiver = that.data.info.id
    }
    var token = app.globalData.userInfo.token
    var type = 'PICTURE'
    var sender = app.globalData.userInfo.userInfo.id
    var roomId = that.data.roomId
    var sendTime = util.formatTime(new Date());
    var senderAvatar = app.globalData.userInfo.userInfo.avatar
    var id = app.globalData.userInfo.userInfo.id
    wx.chooseImage({
      success: function(res) {
        var tempFilePaths = res.tempFilePaths
        console.log(tempFilePaths)
        console.log(tempFilePaths.length)
        for (var i = 0; i < tempFilePaths.length; i++)
        {
          console.log(i)
        wx.uploadFile({
          url: 'https://sdu-miniprogram.cn:8888/api/miniprogram/fileInfo/upload',
          filePath: tempFilePaths[i],
          header:{
            "Content-Type":"multipart/form-data"
          },
          name: 'myFile',
          success(res){
            var data =JSON.parse(res.data)
            console.log(data)
            //得到url
            var url=data.url
              wx.request({
                url: 'https://sdu-miniprogram.cn:8888/api/miniprogram/chatInfo/sendMessage',
              method:'POST',
              data:{
                token:token,
                message:{
                  id:id,
                  roomId:roomId,
                  type:type,
                  sendTime:sendTime,
                  content:url,
                  sender:sender,
                  receiver:receiver,
                  senderAvatar:senderAvatar

                }

              },
              success:function(res)
              {
                console.log(res)

              }
              })
          }
        })
        var content = tempFilePaths[i]
          //同步到聊天
        var json = {
          id: id,
          roomId: roomId,
          type: 'PICTURE',
          senderAvatar: app.globalData.userInfo.userInfo.avatar,
          sendTime: sendTime,
          content: content,
          sender: app.globalData.userInfo.userInfo.id
        }

        app.globalData.goEasy.publish({
          channel: channel, //替换为您自己的channel
          message: JSON.stringify(json)//替换为您想要发送的消息内容
        });
        }

        }
    })
  },
  goTovedio:function()
  {
    var that=this
    var token = app.globalData.userInfo.token
    var type = 'VEDIO'
    var sender = app.globalData.userInfo.userInfo.id
    var roomId = that.data.roomId
    var sendTime = util.formatTime(new Date());
    var senderAvatar = app.globalData.userInfo.userInfo.avatar
    var id = app.globalData.userInfo.userInfo.id
    if (that.data.type == 'room') {
      var receiver = ''
      var channel = "group" + that.data.roomId
    }
    else {
      var channel = "private" + app.globalData.userInfo.userInfo.id + that.data.info.id
      var receiver = that.data.info.id
    }
    
    wx.chooseVideo({
      sourceType: ['album', 'camera'],
      maxDuration: 60,
      camera: ['front', 'back'],
      success(res) {
        console.log(res)
        var tempFilePath=''
        var pic = ''
        //得到视频地址
        wx.uploadFile({
          url: 'https://sdu-miniprogram.cn:8888/api/miniprogram/fileInfo/upload',
          filePath: res.tempFilePath,
          header: {
            "Content-Type": "multipart/form-data"
          },
          name: 'myFile',
          success(res) {
            var data = JSON.parse(res.data)
            console.log(data)
            that.data.vedio=data.url
            //得到全部的url
            console.log(url)
            var url=JSON.stringify(url)
            //同步到聊天 刚刚是没有得到视频地址
            var json = {
              id: id,
              roomId: roomId,
              type: 'VEDIO',
              senderAvatar: app.globalData.userInfo.userInfo.avatar,
              sendTime: sendTime,
              content: that.data.vedio,
              sender: app.globalData.userInfo.userInfo.id
            }
            app.globalData.goEasy.publish({
              channel: channel, //替换为您自己的channel
              message: JSON.stringify(json)//替换为您想要发送的消息内容
            });
            wx.request({
            url: 'https://sdu-miniprogram.cn:8888/api/miniprogram/chatInfo/sendMessage',
            method: 'POST',
            data: {
              token: token,
              message: {
                id: id,
                roomId: roomId,
                type: type,
                sendTime: sendTime,
                content: that.data.vedio,
                sender: sender,
                receiver: receiver,
                senderAvatar: senderAvatar
              }
            },
            success: function (res) {
              console.log(res)
            }
          })

          }
        })
      }
    })
   

  },
  openFile:function(e)
  {
    console.log(e.currentTarget.dataset.src)
    //下载简历
    wx.downloadFile({
      url: e.currentTarget.dataset.src,
      success: function (res) {
        console.log(res)
        var filePath = res.tempFilePath
        console.log(filePath)
        wx.openDocument({
          filePath: filePath,
          // fileType: 'pdf',
          success: function (res) {
            console.log("打开文档成功")
            console.log(res);
          },
        })
      }
      })
  },
  touchStart:function(e)
  {
    //开始录音
    const options = {
      duration: 10000,//指定录音的时长，单位 ms
      sampleRate: 16000,//采样率
      numberOfChannels: 1,//录音通道数
      encodeBitRate: 96000,//编码码率
      format: 'mp3',//音频格式，有效值 aac/mp3
      frameSize: 50,//指定帧大小，单位 KB
    }
    //开始录音
    recorderManager.start(options);
    recorderManager.onStart(() => {
      console.log('recorder start')
    });
    //错误回调
    recorderManager.onError((res) => {
      console.log(res);
    })
    

  },
  touchEnd:function(e)
  {
    var that = this
    var token = app.globalData.userInfo.token
    var type = 'VOICE'
    var sender = app.globalData.userInfo.userInfo.id
    var roomId = that.data.roomId
    var sendTime = util.formatTime(new Date());
    var senderAvatar = app.globalData.userInfo.userInfo.avatar
    var id = app.globalData.userInfo.userInfo.id
    if (this.data.type == 'friend') {
      var channel = "private" + app.globalData.userInfo.userInfo.id + this.data.info.id
      var receiver = this.data.info.id
    }
    else {
      var channel = "group" + roomId
      var receiver = ''
    }
    console.log('touchEnd', e);
    recorderManager.stop();
    recorderManager.onStop((res) => {
      this.tempFilePath = res.tempFilePath;
      console.log('停止录音', res.tempFilePath)
      const { tempFilePath } = res
      wx.uploadFile({
        url: 'https://sdu-miniprogram.cn:8888/api/miniprogram/fileInfo/upload',
        filePath: res.tempFilePath,
        header: {
          "Content-Type": "multipart/form-data"
        },
        name: 'myFile',
        success: function (res) {
          var data = JSON.parse(res.data)
          console.log(data)
          //同步聊天
          var json = {
            id: id,
            roomId: roomId,
            type: 'VOICE',
            senderAvatar: app.globalData.userInfo.userInfo.avatar,
            sendTime: sendTime,
            content: data.url,
            sender: app.globalData.userInfo.userInfo.id
          }
          app.globalData.goEasy.publish({
            channel: channel, //替换为您自己的channel
            message: JSON.stringify(json)//替换为您想要发送的消息内容
          });

          wx.request({
            url: 'https://sdu-miniprogram.cn:8888/api/miniprogram/chatInfo/sendMessage',
            method: 'POST',
            data: {
              token: token,
              message: {
                id: id,
                roomId: roomId,
                type: type,
                sendTime: sendTime,
                content: data.url,
                sender: sender,
                receiver: receiver,
                senderAvatar: senderAvatar
              }
            },
            success: function (res) {
              console.log(res)
            }
          })
        }
      })
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
    })
    
      //取整
      // var time=that.data.time.toFixed();
    
  },
 
  // 播放录音
  audioPlay: function (e) {
    console.log(e)
    innerAudioContext.autoplay = true
    innerAudioContext.src = e.currentTarget.dataset.src,
    innerAudioContext.onPlay(() => {
        console.log('开始播放')
      })
    innerAudioContext.onError((res) => {
      console.log(res.errMsg)
      console.log(res.errCode)
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {


  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  onReady:function(){
    this.pageScrollToBottom()
  },
  // 滚动到页面底部
  pageScrollToBottom: function () {
    console.log("滚动")
    let that = this;
    wx.createSelectorQuery().select('#x_chat').boundingClientRect(function (rect) {
      console.log(rect)
      wx.pageScrollTo({
        scrollTop: rect.height,
        duration: 10
      })
    }).exec()
  }

})